# -*- coding: utf-8 -*-
# @Time : 2022/6/19 10:50
# @Author : cheney
# @File : simulate_base_station.py
# @Software: PyCharm
# @Site: www.cheney.cc

import socket
from pi.config import *
import threading
import json
from pynput.keyboard import Listener
import time

# 监测按键：https://blog.csdn.net/qq_44741568/article/details/97895880

"""
这里模拟一下基站，发送指令，接收数据

ADSW四个按键充当方向键进行操作
"""
_dir = [False, False, False, False]  # 前后左右四个按钮
new_sock = socket.socket


def on_press(key):
    global _dir
    _dir_old = _dir.copy()
    if "'w'" == str(key):
        print("按下--前进")
        _dir[0] = True

    if "'s'" == str(key):
        print("按下--后退")
        _dir[1] = True

    if "'a'" == str(key):
        print("按下--左转")
        _dir[2] = True

    if "'d'" == str(key):
        print("按下--右转")
        _dir[3] = True

    if _dir != _dir_old:
        my_send(_dir)


def on_release(key):
    global _dir
    _dir_old = _dir.copy()
    if "'w'" == str(key):
        print("松开--前进")
        _dir[0] = False

    if "'s'" == str(key):
        print("松开--后退")
        _dir[1] = False

    if "'a'" == str(key):
        print("松开--左转")
        _dir[2] = False

    if "'d'" == str(key):
        print("松开--右转")
        _dir[3] = False

    if _dir != _dir_old:
        my_send(_dir)


def my_send(dir_list):
    print("send", dir_list)
    packet = {
        "src_ip": "192.168.34.53",
        "dst_ip": "192.168.34.53",

        "pac_type": 1,
        "ctl_type": 0,

        "timestamp": "2022-05-13 18:22:35",

        "data": {
            "dst_pi_id": 123,
            "direction": [False, False, False, False],
            "speed": 50,
            "duration": -1
        }
    }
    packet["data"]["direction"] = dir_list
    global new_sock
    new_sock.send((json.dumps(packet)).encode('utf-8'))


def service_thread(_sock: socket.socket):
    """
    收到新的连接，先判断该连接的类型，然后交给对应的函数处理
    :param _sock: 收发报文对应的socket
    :return:
    """
    # global _dir
    # _dir = [False, False, False, False]  # 前后左右四个按钮
    # while True:
    #     choice = input("输入指令:")
    #     try:
    #         if choice in ["1", "2", "3", "4"]:
    #             _dir[int(choice) - 1] = True
    #         elif choice in ["-1", "-2", "-3", "-4"]:
    #             _dir[-1 * int(choice) - 1] = False
    #         else:  # 停
    #             _dir = [False, False, False, False]
    #         packet["data"]["direction"] = _dir
    #         _sock.send((json.dumps(packet)).encode('utf-8'))
    #     except KeyboardInterrupt:
    #         _sock.close()
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()


if __name__ == '__main__':
    s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建套接字
    s_sock.bind((addr_BaseStation_1, port_BaseStation_1))
    s_sock.listen(5)  # socket的”排队个数“为5 ！！！不是最大连接数

    while True:
        print("listening: ", s_sock)
        new_sock, adress = s_sock.accept()  # 这条命令是阻塞的
        threading.Thread(target=service_thread, args=(new_sock,)).start()  # 收到新的请求就直接投入新的线程并且开始运行
